<?php
namespace app\yxwadmin\controller;
use app\yxwadmin\controller\Admin;
use think\Controller;
use think\Request;
use think\Loader;
use think\Cache;


class Role extends Admin
{
    public function index()
    {
        return $this->view->fetch('role/index');
    }

    public function getList(){
        $limit = input('post.limit','0','trim');
        $offset = input('post.offset','0','trim');
        $sortName = input('post.sortName','id','trim');
        $sortOrder = input('post.sortOrder','asc','trim');        
        $keyword = input('post.keyword','','trim');             

        $where['role_name']=array('like','%'.$keyword.'%');

        $count = model('RoleModel')->where($where)->count(); //查询满足要求的总记录数
        $list = model('RoleModel')->where($where)->field('id,role_name,remark,is_manager,create_time')->order($sortName.' '.$sortOrder)->limit($offset,$limit)->select();
        
        $data['total'] = $count;
        $data['rows'] = $list;
        return $data;
    }

    public function add(){
        if(Request::instance()->isPost() ){
            $data = input('post.');
            $permCodes = input('permCodes');
            $data['create_time']=time();
            $roleinfo = model('RoleModel');
            $res = $roleinfo->allowField(true)->save($data);
            if ($res) {                
                foreach(explode(',',$permCodes) as $permcode){
                    $rdata['permission_code']=$permcode;
                    $rdata['roleid']=$roleinfo->id;
                    $rcount = model("PermissionInRoleModel")->insert($rdata);
                }                
                $ret["code"]=0;
                $ret['msg']="新增成功";
                return $ret;
            }else {
                $ret["code"]=1;
                $ret['msg']="新增失败";
                return $ret;
            }
        }else{  
            $fristPermiss = model('PermissionModel')
            ->where('is_hidden',0)->where('parent_code','')
            ->select();   
            $html='<ul>';         
            foreach($fristPermiss as $frist){
                $twoPermission = model('PermissionModel')
                ->where('is_hidden',0)->where('parent_code',$frist->permission_code)
                ->select();
                $html=$html.'<li class="jstree-open" id="'.$frist->permission_code.'">'.$frist->permission_name.'<ul>';                
                foreach($twoPermission as $two){
                    $threePermission = model('PermissionModel')
                    ->where('is_hidden',0)->where('parent_code',$two->permission_code)
                    ->select();
                    $html=$html.'<li class="jstree-open" id="'.$two->permission_code.'">'.$two->permission_name.'<ul>';
                    foreach($threePermission as $three){
                        $html=$html.'<li data-jstree=\'{"type":"css"}\' id="'.$three->permission_code.'">'.$three->permission_name.'</li>';
                    }
                    $html=$html.'</ul></li>';
                }
                $html=$html.'</ul></li>';
            }
            $html=$html.'</ul>';
            $this->assign('prmhtml', $html);
            return $this->view->fetch("role/add");
        }
    }

    public function edit(){
        if(Request::instance()->isPost() ){
            $data = input('post.');
            $permCodes = input('permCodes');
            $data['create_time']=time();
            $id = input('post.id/d');
            $roleinfo = model('RoleModel');
            unset($data['permCodes']);
            unset($data['id']);
            model('PermissionInRoleModel')->where('roleid',$id)->delete();            
            $res = $roleinfo->where('id',$id)->update($data);
            if ($res) {                
                foreach(explode(',',$permCodes) as $permcode){
                    $rdata['permission_code']=$permcode;
                    $rdata['roleid']= $id;
                    $rcount = model("PermissionInRoleModel")->insert($rdata);
                }                
                $ret["code"]=0;
                $ret['msg']="修改成功";

                //清除缓存
                Cache::clear();

                return $ret;
            }else {
                $ret["code"]=1;
                $ret['msg']="修改失败";
                return $ret;
            }
        }else{
            $id =input('get.id');
            if($id){
                $info = model('RoleModel')->find($id);
                $list = model('PermissionInRoleModel')->where('roleid',$id)->field('permission_code')->select();
                $roleprmlist = collection($list)->toArray();              

                $fristPermiss = model('PermissionModel')
                ->where('is_hidden',0)->where('parent_code','')
                ->select();
                $html='<ul>';         
                foreach($fristPermiss as $frist){
                    $twoPermission = model('PermissionModel')
                    ->where('is_hidden',0)->where('parent_code',$frist->permission_code)
                    ->select();
                    $html=$html.'<li class="jstree-open" id="'.$frist->permission_code.'">'.$frist->permission_name.'<ul>';                
                    foreach($twoPermission as $two){
                        $threePermission = model('PermissionModel')
                        ->where('is_hidden',0)->where('parent_code',$two->permission_code)
                        ->select();
                        $html=$html.'<li class="jstree-open" id="'.$two->permission_code.'">'.$two->permission_name.'<ul>';
                        foreach($threePermission as $three){
                            $has = false;
                            foreach($roleprmlist as $rpt){
                                if($rpt['permission_code']==$three->permission_code){
                                    $has=true;
                                    break;
                                }
                            }
                            if($has){
                                $html=$html.'<li data-jstree=\'{"type":"css","selected":"true"}\' id="'.$three->permission_code.'">'.$three->permission_name.'</li>';
                            }else{
                                $html=$html.'<li data-jstree=\'{"type":"css"}\' id="'.$three->permission_code.'">'.$three->permission_name.'</li>';                        
                            }
                        }
                        $html=$html.'</ul></li>';
                    }
                    $html=$html.'</ul></li>';
                }
                $html=$html.'</ul>';
                $this->assign('prmhtml', $html);            

                $this->assign('info', $info);
            }
            return $this->view->fetch("role/edit");
        }
    } 

    public function del(){
        if(Request::instance()->isPost() ){
            $id = input('id');           
            $res = model('RoleModel')->where('id',$id)->delete();
            model('PermissionInRoleModel')->where('roleid',$id)->delete();
            model('RoleInUsersModel')->where("roleid",$id)->delete();
            if ($res) {
                $ret["code"]=0;
                $ret['msg']="新增成功";
                return $ret;
            }else {
                $ret["code"]=1;
                $ret['msg']="新增失败";
                return $ret;
            }
        }else{
            $ret["code"]=1;
            $ret['msg']="非法操作";
            return $ret;
        }
    }

    public function roleuser(){
        $this->assign('roleid', input('roleid'));
        return $this->view->fetch("role/roleuser");        
    }

    public function getroleuserlist(){
        $limit = input('limit','0','trim');
        $offset = input('offset','0','trim');
        $sortName = input('sortName','b.id','trim');
        $sortOrder = input('sortOrder','asc','trim');        
        $keyword = input('keyword','','trim');
        $roleid = input('roleid','','trim');

        $where['b.real_name']=array('like','%'.$keyword.'%');
        $where['a.roleid'] = $roleid;

        $count = model('RoleInUsersModel')->alias('a')->join('User b','b.id=a.userid')->where($where)->count(); //查询满足要求的总记录数
        $list = model('RoleInUsersModel')->alias('a')->join('User b','b.id=a.userid')->where($where)->order($sortName.' '.$sortOrder)->limit($offset,$limit)->select();
        
        $data['total'] = $count;
        $data['rows'] = $list;
        return $data;
    }

    public function roleuseradd(){
        $this->assign('roleid',input('roleid'));
        return $this->view->fetch("role/roleuseradd");
    }

    public function saveuserrole(){
        $roleid = input("roleid");
        $userIds = input("userIds");        
        foreach(explode(',',$userIds) as $userid){
            $data['roleid'] = $roleid;
            $data['userid'] = $userid;
            model("RoleInUsersModel")->insert($data);   
        }
        $ret["code"]=0;
        $ret['msg']="新增成功";
        return $ret;
    }

    public function delroleuser(){
        $userid = input("Id");
        model("RoleInUsersModel")->where("userid",$userid)->delete();
        $ret["code"]=0;
        $ret['msg']="新增成功";
        return $ret;
    }

    public function assignroles(){
        $userid = input('id');
        $roleList = model("RoleModel")->select();
        $userRoles = model("RoleInUsersModel")->where('userid',$userid)->select();

        $html="";
        foreach($roleList as $role){
            $html=$html.'<li><label class="checkbox-inline i-checks">';
            $has=false;
            foreach($userRoles as $userrole){
                if($role->id == $userrole->roleid){
                    $has=true;
                    break;
                }                
            }
            if($has){
                $html=$html.'<input type="checkbox" value="'.$role->id.'" checked="checked">'.$role->role_name;
            }else{
                $html=$html.'<input type="checkbox" value="'.$role->id.'">'.$role->role_name;
            }
            $html=$html.'</label></li>';
        }


        $this->assign('rolehtml',$html);        
        $this->assign('userid',$userid);
        return $this->view->fetch("role/assignroles");
    }

    public function assignrolessave(){
        $userId = input('userId');
        $roleIds = input('roleIds');

        model("RoleInUsersModel")->where('userid',$userId)->delete();

        foreach(explode(',',$roleIds) as $roleId){
            $data['roleid'] = $roleId;
            $data['userid'] = $userId;
            model("RoleInUsersModel")->insert($data);  
        }

        $ret["code"]=0;
        $ret['msg']="新增成功";
        return $ret;
    }
}